package com.laxcen.basiclib.core.bridgewebview.api;

import android.webkit.JavascriptInterface;

import com.laxcen.basiclib.core.bridgewebview.CompletionHandler;
import com.laxcen.basiclib.core.bridgewebview.bean.AjaxData;
import com.laxcen.basiclib.core.bridgewebview.bean.AjaxParam;
import com.laxcen.basiclib.core.bridgewebview.bean.FileValue;
import com.laxcen.basiclib.core.bridgewebview.bean.KeyValue;
import com.laxcen.basiclib.core.bridgewebview.bean.MqttMessage;
import com.laxcen.basiclib.core.bridgewebview.bean.PushLog;
import com.laxcen.basiclib.core.bridgewebview.bean.PushLogH5;
import com.laxcen.basiclib.core.bridgewebview.bean.SystemConst;
import com.laxcen.basiclib.core.bridgewebview.bean.WinParam;
import com.laxcen.basiclib.core.crashpush.CrashPushManager;
import com.laxcen.basiclib.core.location.LocationHelper;
import com.laxcen.basiclib.core.location.LocationInfo;
import com.laxcen.basiclib.core.record.AudioInfo;
import com.laxcen.basiclib.engine.ApiEngine;
import com.laxcen.basiclib.utils.JsonUtil;
import com.laxcen.basiclib.utils.LogUtil;
import com.laxcen.basiclib.utils.StringUtil;

import io.sentry.SentryLevel;

/**
 *  API
 */
public class DefaultApi {

    //处理方法
    private ApiEngine apiEngine;

    public DefaultApi(ApiEngine apiEngine){
        this.apiEngine = apiEngine;
    }

    /**
     *  发送mqtt消息
     * @param obj
     */
    @JavascriptInterface
    public void sendData(Object obj)  {
        MqttMessage mqttMessage = JsonUtil.jsonToBean(obj.toString(),MqttMessage.class);
        apiEngine.sendData(mqttMessage.getTopic(),mqttMessage.getMessage());
    }

    /**
     * 订阅话题
     * @param topic
     */
    @JavascriptInterface
    public void subscribeTopic(Object topic){
        apiEngine.subscribeTopic(topic.toString());
    }

    /**
     *  取消订阅话题
     * @param topic
     */
    @JavascriptInterface
    public void unsubscribeTopic(Object topic){
        apiEngine.unsubscribeTopic(topic.toString());
    }

    /**
     *  数据监听
     * @param handler
     */
    @JavascriptInterface
    public void dataListener(Object obj,CompletionHandler<String> handler){
        apiEngine.dataListener((type, topic, msg1) -> {
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setType(type);
            mqttMessage.setTopic(topic);
            mqttMessage.setMessage(msg1);
            handler.setProgressData(JsonUtil.beanToJson(mqttMessage));
        });
    }

    @JavascriptInterface
    public void pushLog(Object msg){
        PushLogH5 pushLog = JsonUtil.jsonToBean(msg.toString(), PushLogH5.class);
        PushLog pushLogs = new PushLog();
        switch (pushLog.getLevel()){
            case "info":
                pushLogs.setLevel(SentryLevel.INFO);
                break;
            case "error":
                pushLogs.setLevel(SentryLevel.ERROR);
                break;
            case "debug":
                pushLogs.setLevel(SentryLevel.DEBUG);
                break;
            case "fatal":
                pushLogs.setLevel(SentryLevel.FATAL);
                break;
            case "warning":
                pushLogs.setLevel(SentryLevel.WARNING);
                break;
        }
        pushLogs.setType("js");//js调用的
        pushLogs.setMessage(pushLog.getContent());
        CrashPushManager.getInstance().pushLog(pushLogs);
    }

    @JavascriptInterface
    public String getConst(Object obj){
        SystemConst systemConst = apiEngine.getConst();
        return JsonUtil.beanToJson(systemConst);
    }


    @JavascriptInterface
    public void setCanBackToMain(Object obj){
        boolean b = "true".equals(obj.toString());
        apiEngine.setCanBackToMain(b);
    }

    @JavascriptInterface
    public void openWin(Object obj){
        WinParam winParam = JsonUtil.jsonToBean(obj.toString(),WinParam.class);
        apiEngine.openWin(winParam);
    }

    @JavascriptInterface
    public void closeWin(Object obj){
        apiEngine.closeWin();
    }


    @JavascriptInterface
    public String getWinParam(Object msg){
        WinParam winParam = apiEngine.getWinParam();
        return JsonUtil.beanToJson(winParam);
    }

    @JavascriptInterface
    public void finishApp(Object msg){
        apiEngine.finishApp();
    }

    @JavascriptInterface
    public void rebootApp(Object msg){
        apiEngine.reloadApp();
    }


    @JavascriptInterface
    public String ajax(Object obj, CompletionHandler<String> handler){
        AjaxParam param = JsonUtil.jsonToBean(obj.toString(),AjaxParam.class);
        if(param==null){
            AjaxData ajaxData = new AjaxData();
            ajaxData.setStatus(0);
            ajaxData.setMsg("传入参数不能为空!");
            handler.complete();
            return "error";
        }
        /**
         * -1 用户取消
         * 0 请求失败
         * 1 开始请求/上传
         * 2 请求中/上传中
         * 3 请求/上传完成
         * 4 全部请求/上传完成
         * 5 请求超时
         */
        return apiEngine.ajax(param, ajaxData -> {
            switch (ajaxData.getStatus()){
                case 1:
                case 2:
                case 3:
                    handler.setProgressData(JsonUtil.beanToJson(ajaxData));
                    break;
                default:
                    handler.complete(JsonUtil.beanToJson(ajaxData));
                    break;
            }
        });
    }

    @JavascriptInterface
    public void cancelAjax(Object obj){
        apiEngine.cancelAjax(obj.toString());
    }


    @JavascriptInterface
    public void download(Object obj,CompletionHandler<String> handler){
        apiEngine.download(obj.toString(), downloadInfo -> {
            handler.setProgressData(JsonUtil.beanToJson(downloadInfo));
        });
    }

    @JavascriptInterface
    public void pauseDownload(Object obj){
        apiEngine.pauseDownload(obj.toString());
    }

    @JavascriptInterface
    public void cancelDownload(Object obj){
        apiEngine.cancelDownload(obj.toString());
    }


    @JavascriptInterface
    public void readFile(Object obj, CompletionHandler<String> handler){
       apiEngine.readFile(obj.toString(),txt -> handler.complete(txt));
    }

    @JavascriptInterface
    public void writeFile(Object obj, CompletionHandler<String> handler){
        FileValue fileValue = JsonUtil.jsonToBean(obj.toString(),FileValue.class);
        apiEngine.writeFile(fileValue.getPath(), fileValue.getContent(), txt -> handler.complete(txt));
    }


    @JavascriptInterface
    public String getData(Object obj){
        LogUtil.e("getData",obj.toString());
        String d = apiEngine.getData(obj.toString(),"");
        LogUtil.e("getData",d);
        return d;
    }


    @JavascriptInterface
    public void putData(Object obj){
        LogUtil.e("sdfdgsdsd",obj.toString());
        KeyValue keyValue = JsonUtil.jsonToBean(obj.toString(),KeyValue.class);
        LogUtil.e("putData",JsonUtil.beanToJson(keyValue));
        apiEngine.putData(keyValue.getKey(),keyValue.getValue());
    }


    @JavascriptInterface
    public void getLocation(Object obj, CompletionHandler<String> handler){
        apiEngine.getLocation(new LocationHelper.OnResult() {
            @Override
            public void onSuccess(LocationInfo locationInfo) {
                handler.complete(JsonUtil.beanToJson(locationInfo));
            }

            @Override
            public void onError() {
                LocationInfo locationInfo = new LocationInfo();
                locationInfo.setOk(false);
                handler.complete(JsonUtil.beanToJson(locationInfo));
            }
        });
    }


    @JavascriptInterface
    public void callTel(Object obj){
         apiEngine.callTel(obj.toString());
    }

    @JavascriptInterface
    public void showToast(Object msg){
        apiEngine.showToast(msg.toString());
    }


    @JavascriptInterface
    public void openCamera(Object obj){
        apiEngine.openCamera();
    }


    @JavascriptInterface
    public void openPhoto(Object obj){
        apiEngine.openPhoto();
    }


    @JavascriptInterface
    public void startRecord(Object obj, CompletionHandler<String> handler){
        int time = 0 ;
        if(!StringUtil.isEmpty(obj.toString())){
            try {
                time = Integer.parseInt(obj.toString());
            }catch (Exception e){
            }
        }
        apiEngine.startRecord(audioInfo -> {
            if(AudioInfo.ACTION_RECORDING.equals(audioInfo.getAction())){
                handler.setProgressData(JsonUtil.beanToJson(audioInfo));
            }else{
                handler.complete(JsonUtil.beanToJson(audioInfo));
            }
        },time);
    }


    @JavascriptInterface
    public void pauseRecord(Object msg){
         apiEngine.pauseRecord();
    }

    @JavascriptInterface
    public void stopRecord(Object obj){
        apiEngine.stopRecord("1".equals(obj.toString().toLowerCase()));
    }

    @JavascriptInterface
    public void checkFace(Object msg, CompletionHandler<String> handler){
        handler.complete("未安装该插件");
    }

    @JavascriptInterface
    public void getFaceBitmap(Object msg, CompletionHandler<String> handler){
        handler.complete("未安装该插件");
    }

    @JavascriptInterface
    public void dongleCheck(Object msg, CompletionHandler<String> handler){
        handler.complete("未安装该插件");
    }

    @JavascriptInterface
    public void checkUpdate(Object obj){
        apiEngine.checkUpdate(true);
    }


    //获取设备指纹
    @JavascriptInterface
    public void getFingerprint(Object obj, CompletionHandler<String> handler){
        apiEngine.getFingerprint(txt -> handler.complete(txt));
    }

}